<template>
  <div class="container">
    <el-card class="box-card">
      <div class="item-grid">
        <el-card v-for="item in pagedItems" :key="item.id" class="item-card" @click="openItemDialog(item)">
          <div class="card-vertical">
            <img :src="item.product_image || 'https://via.placeholder.com/100?text=No+Image'" :alt="item.product_name" class="product-image" @error="handleImageError" style="width: 200px;"/>
            <div class="card-content">
              <div class="card-title">{{ item.product_name }}</div>
              <div class="card-description">{{ item.product_description }}</div>
              <div class="card-price">¥{{ item.product_price }}</div>
            </div>
          </div>
        </el-card>
      </div>
  
      <el-pagination v-model:currentPage="currentPage" :page-size="itemsPerPage" :total="totalItems"
        layout="prev, pager, next" @current-change="handlePageChange" class="pagination" />
    </el-card>
  </div>
  <el-dialog v-model="dialogVisible" :title="currentItem.product_name">
    <div v-if="currentItem && currentItem.user_id">
      <template v-if="Number(currentItem.user_id) === Number(userId)">
        <p>商品名称: {{ currentItem.product_name }}</p>
        <p>商品描述: {{ currentItem.product_description }}</p>
        <p>商品价格: ¥{{ currentItem.product_price }}</p>
        <p>浏览量: {{ currentItem.views || 0 }}</p>
        <img :src="currentItem.product_image || 'https://via.placeholder.com/100?text=No+Image'" alt="商品图片" style="width: 200px; margin-top: 10px;">
      </template>
      <template v-else>
        <p>商品名称: {{ currentItem.product_name }}</p>
        <p>商品描述: {{ currentItem.product_description }}</p>
        <p>商品价格: ¥{{ currentItem.product_price }}</p>
        <el-input 
          v-model.number="quantity" 
          placeholder="请输入数量" 
          type="number" 
          :min="1"
          style="margin-top: 15px;"
        />
        <img :src="currentItem.product_image || 'https://via.placeholder.com/100?text=No+Image'" alt="商品图片" style="width: 200px; margin-top: 10px;">
      </template>
    </div>
  
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button 
        v-if="Number(currentItem.user_id) !== Number(userId)" 
        type="primary" 
        @click="addToCart"
      >
        添加到购物车
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElNotification } from 'element-plus'
import axios from 'axios'

const items = ref([])
const totalItems = ref(0)
const itemsPerPage = ref(8) // 每页显示8个商品（2行4列）
const currentPage = ref(1)
const dialogVisible = ref(false)
const currentItem = ref({})
const quantity = ref(1)
const userId = ref(Number(localStorage.getItem('userId'))) // 转换为数字类型

// 计算当前页的商品
const pagedItems = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value
  const end = start + itemsPerPage.value
  return items.value.slice(start, end)
})

const fetchItems = async () => {
  try {
    const response = await axios.get('http://localhost:3000/items')
    items.value = response.data.map(item => ({
      ...item,
      // 统一用户ID字段名称
      user_id: item.user_id || item.seller_id || null
    }))
    totalItems.value = items.value.length
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: 'Failed to fetch items',
      type: 'error',
    })
    console.error('Error fetching items:', error)
  }
}

onMounted(() => {
  fetchItems()
})

const handleCarouselChange = (activeIndex) => {
  console.log('carousel changed to:', activeIndex)
}

const handlePageChange = (newPage) => {
  currentPage.value = newPage
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
}


const openItemDialog = (item) => {
  if (!item || typeof item !== 'object') return
  
  currentItem.value = {
    ...item,
    user_id: item.user_id || item.sellerId || null
  }
  
  quantity.value = 1
  dialogVisible.value = true
}

const addToCart = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.post(
      'http://localhost:3000/cart',
      { item_id: currentItem.value.item_id, quantity: quantity.value },
      {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    )
    ElNotification({
      title: 'Success',
      message: '商品已添加到购物车',
      type: 'success',
    })
    dialogVisible.value = false
  } catch (error) {
    ElNotification({
      title: 'Error',
      message: '添加到购物车失败',
      type: 'error',
    })
    console.error('Error adding to cart:', error)
  }
}
</script>

<style scoped>
.container {
  max-width: 100%;
  margin: 0 auto;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
}

.item-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  padding: 0;
  max-width: 1440px;
  margin: 0 auto;
}

.item-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  background: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: none;
}

.item-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 24px rgba(63, 81, 181, 0.2);
}

.card-vertical {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.product-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.card-content {
  padding: 16px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #2c3e50;
}

.card-description {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 12px;
  flex-grow: 1;
  line-height: 1.5;
}

.card-price {
  font-size: 18px;
  font-weight: 700;
  color: #3f51b5;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 对话框样式优化 */
.el-dialog {
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.el-dialog__header {
  background: linear-gradient(135deg, #3f51b5 0%, #303f9f 100%);
  margin: 0;
  padding: 16px 20px;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.el-dialog__title {
  color: white !important;
  font-weight: 600;
}

.el-dialog__body {
  padding: 20px;
}

.el-input__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
}
</style>